<?php

Class Book extends Connect {
    
    static $book = array();
    static $greens = array();
    
    /**
     * Возвращает главу из книги, если $glava = 0 все главы 
    */
    static function getBook($glava = 0, $other = ''){
        
        if($glava != 0){
            $_glavaSql = "AND `glava` = '".$glava."'";
        }else{
            $_glavaSql = "";
        }        
        if(isset(Book::$book[$glava]) && count(Book::$book[$glava]) > 0){
            return Book::$book[$glava];
        }
        Habars::getHabars();
        $sql = "SELECT  glava.id as id,
				        glava.name as name,
                        glava.glava as glava,
                        glava.descript as descript,                        
                        
                        green.id as greenid,
                        green.name as greenname,
                        green.descript as greendescript,                        
                        green.doit as greendoit,
                        green.level as greenlevel,
                        green.image as greenimage,
                        green.practic as practic,
                        
                        green.discount as greendiscount,
                        green.buy1 as greenbuy1,
                        green.buy2 as greenbuy2,
                        green.sell1 as greensell1,
                        green.sell2 as greensell2,
                        green.edu1 as greenedu1,
                        green.edu2 as greenedu2,
                        
                        mantra.name as mantra,
                        mantra.value as mantra_value,                        
                        
                        recept.id as receptid,
                        recept.idhabar as receptidhabar,
                        recept.idelement as receptidelement,
                        recept.count as receptcount                          
                          
                FROM (SELECT * FROM  `".PREFIX_STATIC."green` WHERE `parent` = '0' ".$_glavaSql." ".$other." ) glava
                LEFT JOIN
                (SELECT * FROM  `".PREFIX_STATIC."green` ORDER BY `level` ASC) green ON glava.id = green.parent
                LEFT JOIN 
                (SELECT * FROM  `".PREFIX_STATIC."mantras` WHERE `type` = 'green') mantra ON mantra.good = green.id
                LEFT JOIN 
                (SELECT * FROM  `".PREFIX_STATIC."recepts`) recept ON green.id = recept.idgreen
                ";
        #_echo($sql);
        if(!$result = DBConnect::query($sql, 'book')){
            return mysql_error();
        }               
        while($arr = DBConnect::getOne($result, 'book')){
            $i = $arr['id'];
            if(!isset(Book::$book[$i])){
                Book::$book[$i] = array();// $arr;
                Book::$book[$i]['id'] = $arr['id'];
                Book::$book[$i]['glava'] = $arr['glava'];
                Book::$book[$i]['name'] = $arr['name'];
                Book::$book[$i]['descript'] = $arr['descript'];                
                
                Book::$book[$i]['green'] = array();                 
                if( !empty($arr['greenid']) ){
                    Book::$book[$i]['green'][$arr['greenid']]['recept'] = array();   
                    Book::$book[$i]['green'][$arr['greenid']]['mantra'] = array();    
                }
                
            }
            #_echo($arr['greenid']);
            
            elseif(  $arr['greenid'] == null || 
                    empty($arr['greenid']) || 
                    $arr['greenid'] == '' || 
                    intval( $arr['greenid']) == 0 ){
                _echo($arr['greenid']);
                continue;    
            }
            
            #_echo($arr['id']. " >>>> ". $arr['greenid']);
            if( !empty($arr['greenid']) ){                
            #_echo(intval( $arr['greenid']) );
            Book::$book[$i]['green'][$arr['greenid']]['id'] = $arr['greenid'];
            Book::$book[$i]['green'][$arr['greenid']]['level'] = $arr['greenlevel']; 
            Book::$book[$i]['green'][$arr['greenid']]['name'] = $arr['greenname'];
            Book::$book[$i]['green'][$arr['greenid']]['descript'] = $arr['greendescript'];
            Book::$book[$i]['green'][$arr['greenid']]['doit'] = $arr['greendoit'];
            Book::$book[$i]['green'][$arr['greenid']]['practic'] = $arr['practic'];
            Book::$book[$i]['green'][$arr['greenid']]['image'] = MEDIA_URL.$arr['greenimage'];
            
            Book::$book[$i]['green'][$arr['greenid']]['discount'] = $arr['greendiscount'];
            Book::$book[$i]['green'][$arr['greenid']]['buy1'] = $arr['greenbuy1'];
            Book::$book[$i]['green'][$arr['greenid']]['buy2'] = $arr['greenbuy2'];
            Book::$book[$i]['green'][$arr['greenid']]['sell1'] = $arr['greensell1'];
            Book::$book[$i]['green'][$arr['greenid']]['sell2'] = $arr['greensell2'];
            Book::$book[$i]['green'][$arr['greenid']]['edu1'] = $arr['greenedu1'];
            Book::$book[$i]['green'][$arr['greenid']]['edu2'] = $arr['greenedu2'];
            Book::$book[$i]['green'][$arr['greenid']]['type'] = "potion";
            
            if(!empty($arr['receptid']) ){
                Book::$book[$i]['green'][$arr['greenid']]['recept'][$arr['receptid']]['habar'] = @$arr['receptidhabar'];
                Book::$book[$i]['green'][$arr['greenid']]['recept'][$arr['receptid']]['element'] = @$arr['receptidelement'];
                Book::$book[$i]['green'][$arr['greenid']]['recept'][$arr['receptid']]['type'] = @Habars::$habars[$arr['receptidhabar']]['type'] ;
                Book::$book[$i]['green'][$arr['greenid']]['recept'][$arr['receptid']]['count'] = @$arr['receptcount'];    
            }
            if( !isset(Book::$book[$i]['green'][$arr['greenid']]['mantra']) ){
                Book::$book[$i]['green'][$arr['greenid']]['mantra'] = array();
            }
            /**/
            if( !empty($arr['mantra']) ){
                if( !isset(Book::$book[$i]['green'][$arr['greenid']]['mantra']['info'])){
                    if($arr['mantra'] == 'id'){
                        Book::$book[$i]['green'][$arr['greenid']]['mantra']['info'] = Magic::getInfo($arr['mantra_value']);
                    }
                }
                if($arr['mantra'] == 'image' ){
                    $arr['mantra_value'] = ( !Pet::is_url($arr['mantra_value']) ? MEDIA_URL.$arr['mantra_value'] : $arr['mantra_value']  );
                }
                Book::$book[$i]['green'][$arr['greenid']]['mantra'][$arr['mantra']] = $arr['mantra_value'];    
            }
            
            /*if($arr['mantra']){
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['id'] = @$arr['mantra'];                
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['element'] = @$arr['mantra_element'];
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['idelement'] = @$arr['mantra_idelement'];
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['value'] = @$arr['mantra_value'];
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['timelive'] = @$arr['mantra_timelive'];
                Book::$book[$i]['green'][$arr['greenid']]['mantra']['force'] = @$arr['mantra_force'];
            }*/
            }
        }                   
        return Book::$book;
        #return $sql;
    }
    
    
    /**
     * Возвращает один рецепт
    */
    static function getGreen($id){
        
        if(count(Book::$book) == 0 ){
            Book::getBook();
        }
        foreach(Book::$book as $glava){
            #return $galava;
            if(isset($glava['green'][$id])){
                Book::$greens[$id] = $glava['green'][$id];
                return $glava['green'][$id];                
            }
        }
        Connect::_error("Рецепт не найден");
        return false;                
    }
    
    /**
     * Возвращает один случайный рецепт
    */
    static function getRandomGreen($count = 1){        
        if(count(Book::$book) == 0 ){
            Book::getBook();
        }
        $arr = array();        
        foreach(Book::$book as $glava){           
            $arr = array_merge($arr, $glava['green']);             
        }                
        $_arr = array_rand($arr, $count) ;
        
        if($count == 1){
            return array( $arr[$_arr] );    
        } 
               
        $a = array();  
        foreach($_arr as $k => $v){
            $a[] = $arr[$v] ;
        }              
        return $a;
    }
    
    /**
     * 
    */
    static function getOfLevels($level1, $level2){
        Book::getBook();
        $arr = array();
        #return $level2;
        foreach(Book::$book as $key => $val){
            #return $val;
            foreach($val['green'] as $keyG => $valG){
                if(intval($valG['level']) > $level1  && intval($valG['level']) <= $level2){
                    $arr[] = $valG;       
                }
            }
        }
        return $arr;
    }
    
    /**
     *obj = Object (@df60599)	
	buy1 = "15"	
	buy2 = "5"	
	descript = "варево1-2"	
	image = "http://192.168.6.194/media/pznahar/potion/19.png"	
	level = "1"	
	magic = Object (@9ff7269)	
		element = ""	
		force = "50"	
		id = "9"	
		idelement = ""	
		timelive = ""	
		value = ""	
	name = "варево1-2"	
	practic = ""	
	recept = Object (@9182ad9)	
		[0] = Object (@917ee69)	
			count = "1"	
			element = "16"	
			habar = "12"	
		[1] = Object (@917eca1)	
			count = "1"	
			element = "6"	
			habar = "3"	
	sell1 = "15"	
	sell2 = "5"	

     *  
    */
    function save($data){                 
        #return $data;
        if( !is_array($data) ) return false;
        $sql = "UPDATE `".PREFIX_STATIC."green` SET `name` = '".$data['name']."', 
                                                    `descript` = '".$data['descript']."', 
                                                    `level` = '".$data['level']."', 
                                                    `practic` = '".$data['practic']."', 
                                                    `buy1` = '".$data['buy1']."', 
                                                    `buy2` = '".$data['buy2']."', 
                                                    `sell1` = '".$data['sell1']."', 
                                                    `sell2` = '".$data['sell2']."', 
                                                    `discount` = '".$data['discount']."',
                                                    `edu1` = '".$data['edu1']."',
                                                    `edu2` = '".$data['edu2']."',
                                                    `parent` = '".$data['parent']."',
                                                    `image` = '".str_replace(MEDIA_URL, '', $data['image']) ."'
                                                    WHERE `id` = '".$data['id']."'  ";        
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $sql = "DELETE FROM `".PREFIX_STATIC."recepts` WHERE `idgreen` = '".$data['id']."' ";
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $sql = "INSERT INTO `".PREFIX_STATIC."recepts` ( `idgreen`, `idhabar`, `idelement`, `count` ) VALUES ";
        $i = 1;
        foreach($data['recept'] as $key => $val){
            $sql .= "( '".$data['id']."',  '".$val['habar']."',  '".$val['element']."', '".$val['count']."' )" ;
            $sql .= ($i < count($data['recept']))? ", " : "" ;
            $i++;
        }
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $del = "DELETE FROM `".PREFIX_STATIC."mantras` WHERE 
                `type` = 'green' AND `good` = '".$data['id']."' ";
        #_echo($del);
        if(!DBConnect::query($del)){
            $this->_error(mysql_error());
            return false;
        }
        #return $data['id'];
        return $this->insertMantras($data['mantra'], 'green', $data['id']);        
        #return true;
    }    
    
    function add($data){
        if( !is_array($data) ) return false;
        $sql = "INSERT INTO `".PREFIX_STATIC."green` (`parent`, `name`, `descript`, `practic`, `level`,
                                                      `buy1`, `buy2`, `sell1`, `sell2`,
                                                      `discount`, `edu1`, `edu2`, `image`    )
                                                      VALUES
                                                      ('".$data['parent']."',
                                                        '".$data['name']."', '".$data['descript']."', 
                                                       '".$data['practic']."', '".$data['level']."', 
                                                       '".$data['buy1']."', '".$data['buy2']."',
                                                       '".$data['sell1']."', '".$data['sell2']."',
                                                       '".$data['discount']."', '".$data['edu1']."',
                                                       '".$data['edu2']."', '".str_replace(MEDIA_URL, '', $data['image']) ."') ";       
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $idGreen = mysql_insert_id();

        $sql = "INSERT INTO `".PREFIX_STATIC."recepts` ( `idgreen`, `idhabar`, `idelement`, `count` ) VALUES ";
        $i = 1;
        foreach($data['recept'] as $key => $val){
            $sql .= "( '".$idGreen."',  '".$val['habar']."',  '".$val['element']."', '".$val['count']."' )" ;
            $sql .= ($i < count($data['recept']))? ", " : "" ;
            $i++;
        }
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        if( !$this->insertMantras($data['mantra'], 'green', $idGreen) ) {
            return false;
        }        
        return $idGreen;
    }
    
    function deleteGlava($idGlava){
        Book::getBook();
        foreach(Book::$book as $g => $vg){
            if(intval($vg['glava']) == intval($idGlava) ){
                if(is_array($vg['green']) && count($vg['green']) > 0 ) foreach($vg['green'] as $gr => $vgr){
                    $this->delete($vgr['id']);
                }
            }
        }
        $del = "DELETE FROM `".PREFIX_STATIC."green` WHERE `glava` = '".$idGlava."' ";
        if(!DBConnect::query($del)){
            $this->_error(mysql_error());
            return false;
        }
        return true;
    }
    
    function delete($idGreen){
        $sql = "DELETE FROM `".PREFIX_STATIC."green` WHERE `id` = '".$idGreen."' ";
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        $del = "DELETE FROM `".PREFIX_STATIC."mantras` WHERE 
                `type` = 'green' AND `good` = '".$idGreen."' ";
        if(!DBConnect::query($del)){
            $this->_error(mysql_error());
            return false;
        }
        return true;
    }
    
    private function insertMantras($mantras, $type, $good){
        if(count($mantras) == 0) return true;        
        $sql = "INSERT INTO `".PREFIX_STATIC."mantras` (`type`, `good`, `name`, `value`)
                                                         VALUES ";
        $i = 1;
        foreach($mantras as $key => $val){
            if($key != 'info'){
                if($key == 'image'){
                    $val = str_replace(MEDIA_URL, '', $val);
                }
                $sql .= "('".$type."', '".$good."', '".$key."', '".$val."')";
                $sql .= ($i < count($mantras))? " , " : "" ;    
            }
            $i++;
        }
        #_echo($sql);
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        return true;
     }
     
     function saveGlava($data){
        if( !is_array($data) ) return false;
        $sql = "UPDATE `".PREFIX_STATIC."green` SET `name` = '".$data['name']."', 
                                                    `descript` = '".$data['descript']."' 
                                                    WHERE `glava` = '".$data['id']."'  ";        
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }             
        return true;
     }
     function addGlava($data){
        if( !is_array($data) ) return false;
        $get = "SELECT * FROM `".PREFIX_STATIC."green` WHERE `parent` = '0' ORDER BY `glava` DESC LIMIT 1 ";
        if(!$result = DBConnect::query($get)){
            $this->_error(mysql_error());
            return false;
        }
        $glava = DBConnect::getOne($result);
        $sql = "INSERT INTO `".PREFIX_STATIC."green` (`parent`, `name`, `descript`, `glava` )
                                                      VALUES
                                                      ('0',
                                                        '".$data['name']."', 
                                                        '".$data['descript']."',
                                                        '".(intval($glava['glava']) + 1) ."') ";       
        if(!DBConnect::query($sql)){
            $this->_error(mysql_error());
            return false;
        }
        return mysql_insert_id();
     }
}
?>